
import java.util.LinkedList;

public class WriteThread implements Runnable {
	private LinkedList<Measurement> queue;
	private Database db;
	private static int QUEUE_SIZE = 8000;
	
	public WriteThread(Database db) {
		this.db = db;
		queue = new LinkedList<Measurement>();
	}
	
	public synchronized void add(Measurement measurement) {
		queue.addLast(measurement);
		//System.out.println("Measurement added to queue");
		notify();
		//System.out.println(queue.size());
	}
	
	
	public synchronized void waitForMeasurements() {
		while (queue.size() < QUEUE_SIZE) {
			try {
				//System.out.println("Waiting for measurements...");				
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		int stn =  0;
		StringBuffer query = new StringBuffer("INSERT INTO measurement (stn, date, time, temp, dewp, stp, slp, visib, wdsp, prcp, sndp, frshtt, cldc, wnddir)" +
				 "VALUES ");
		for(Measurement m : queue) {
			
			String date = m.getDate();
			String time = m.getTime();
			stn =  m.getStn();
			query.append("(" + m.getStn() + ",'"+ date + "','"+  time + "'," 
						+  "AES_ENCRYPT('"+(m.getTemp())+"','@#dwave$r')," 
						+  "AES_ENCRYPT('"+m.getDewp()+"','@#dwave$r'),"  
						+  "AES_ENCRYPT('"+m.getStp()+"','@#dwave$r'),"  
						+  "AES_ENCRYPT('"+m.getSlp()+"','@#dwave$r')," 
						+  "AES_ENCRYPT('"+m.getVisib()+"','@#dwave$r')," 
						+  "AES_ENCRYPT('"+m.getWdsp()+"','@#dwave$r')," 
						+  "AES_ENCRYPT('"+(m.getPrcp())+"','@#dwave$r')," 
						+  "AES_ENCRYPT('"+m.getSndp()+"','@#dwave$r')," 
						+  "AES_ENCRYPT('"+m.getFrshtt()+"','@#dwave$r')," 
						+  "AES_ENCRYPT('"+m.getCldc()+"','@#dwave$r'),"  
						+  "AES_ENCRYPT('"+m.getWnddir()+"','@#dwave$r'))");
			if(queue.getLast() == m) {
				query.append(";");
			}
			else {
				query.append(",");
			}
		}
		
		queue.clear();

		db.insert(query.toString());

	    System.out.println("Measurement writen to database");
	    System.out.println(stn);
	}
	
	@Override
	public void run() {
		while(true) {
			waitForMeasurements();
		}
	}
}
